﻿package Modules.VolunteerModule{
	
	import Modules.CommunicationsModule.ClientServerCommunications;
	import Modules.CommunicationsModule.PlayerActivityCommunications;
	import Modules.CommunicationsModule.SGCareCommunicationModule;
	import Modules.MainTimeLine;
	import Modules.Utilities;
	
	import flash.display.MovieClip;
	
	public class Volunteer
	{
		// status of a user for event
		public static const NO_STATUS:String = ""
		public static const ATTENDED:String = "attended";
		public static const AVAILABLE:String = "Available";
		public static const CANCELLED:String = "cancelled";
		public static const SIGNED_UP:String = "signup";
		public static const WAITLIST:String = "waitlist";
		
		// class variable
		public var activityTable:Array;
		
		public var playerActivityJoinTable:Array;

		public var volunteerReward:VolunteerReward;
		
		public var currentDate:Date;
		
		public var loadingMutex:int; // when this turns 0, loading will stop (use when checking event status & loading table)

		public function Volunteer(){
			loadingMutex = 0;
			playerActivityJoinTable = [];
			volunteerReward = new VolunteerReward();
			
			initVolunteer();
		}
		
		public function initVolunteer():void{
			// get current month
			currentDate = new Date();

			// load player activity
			PlayerActivityCommunications.loadPlayerActivityJoin();
			
			// load events
			loadEvents(currentDate.getMonth(), currentDate.getFullYear());

			// hide login register button if not needed
			if(MainTimeLine.session.player.volunteerID != null && MainTimeLine.session.player.volunteerID != ""){
				MainTimeLine.root.main.townHallPanel.volunteerPanel.hideLoginRegisterButton();
			}
		}
		
		// given a month, find all events in that month
		public function loadEvents(month:Number, year:Number){
			if(MainTimeLine.root.main.townHallPanel != null){
				MainTimeLine.root.main.townHallPanel.volunteerPanel.messageBox.showMessageBox("", false, false);
			}
			
			// find start day of current month
			var startDate:String = "01/" + Utilities.convertMonthToString(month) + "/" + year;
			
			// find end day of current month
			var endDate:String = Utilities.getDaysInMonth(month) + "/" + Utilities.convertMonthToString(month) + "/" + year;
			
			loadingMutex += 1;
			SGCareCommunicationModule.getVolunteerEvents(startDate, endDate);
			
			MainTimeLine.loadedVolunteerEvents = false;
			
			if(MainTimeLine.root.main.townHallPanel != null){
				MainTimeLine.root.main.townHallPanel.volunteerPanel.loadingPanel.startLoading();
			}
		}
		
		// set activity table
		public function setActivityTable(activitiesXML:XML){
			loadingMutex--;
			MainTimeLine.loadedVolunteerEvents = true;
			
			// reset activity table
			activityTable = [];
			
			for(var i:int=0; i<activitiesXML.Activity.length(); i++){
				activityTable.push(new Activity(activitiesXML.Activity[i]));
			}

			if(activityTable.length > 0)
				searchFriendsInActivity();
			else{ // no activity
				MainTimeLine.loadedVolunteerEvents = true;
				
				// finish loading?
				if(loadingMutex == 0){
					MainTimeLine.root.main.townHallPanel.volunteerPanel.loadingPanel.stopLoading();
				}
			}
			
			// rebuild calendar in game
			MainTimeLine.root.main.townHallPanel.volunteerPanel.rebuildCalendar();

			// update UI
			MainTimeLine.root.main.townHallPanel.volunteerPanel.refreshVolunteerActivities();
			
			// check whether user has login, update check status if did log in
			if(MainTimeLine.session.player.volunteerID && MainTimeLine.session.player.volunteerID != ""){
				checkAllUserActivityStatus();
			}
			else{
				
				MainTimeLine.loadedVolunteerEvents = true;

				// finish loading?
				if(loadingMutex == 0){
					MainTimeLine.root.main.townHallPanel.volunteerPanel.loadingPanel.stopLoading();
				}
				
				// default no status
				for(var i:int=0; i<activitiesXML.Activity.length(); i++){
					loadingMutex++;
					setActivityStatus(activityTable[i].activityID, NO_STATUS);
				}
			}
		}
		
		// login using sg cares volunteer id
		public function login(nricFin:String, password:String){
			
			MainTimeLine.root.main.townHallPanel.volunteerPanel.loadingPanel.startLoading();
			SGCareCommunicationModule.login(nricFin, password);
		}
		
		// complete login
		public function completeLogin(loginXML:XML){
			
			MainTimeLine.root.main.townHallPanel.volunteerPanel.loadingPanel.stopLoading();
			// check whether login successful
			var loginResult:XML = loginXML.VolunteerAuthentication[0];
			
			// login failed?
			if(loginResult == null){
				// Failed! tell UI wrong detail
				MainTimeLine.root.main.townHallPanel.volunteerPanel.loginForm.statusText.text = "Wrong NRICFIN or password";
			}
			else{
				
				// successful.
				// save to db (so next time no need to log in) 
				ClientServerCommunications.updateVolunteerID(loginResult.VolID);

				// update local copy
				MainTimeLine.session.player.volunteerID = loginResult.VolID;
				
				// close login ui
				MainTimeLine.root.main.townHallPanel.volunteerPanel.loginForm.closeLoginPanel();
				
				// welcome player
				var welcomeString:String = "Thank you for logging in. You can now sign up for activities.\n\n";
				welcomeString += "Please note that you have to attend an orientation session before you can sign up for volunteer activities.\n\n";
				welcomeString += "For more information, please visit <font color='#0066FF'><a href='http://www.sgcares.org' target='_blank'>SG Cares</a></font>.";
	
				MainTimeLine.root.main.townHallPanel.volunteerPanel.messageBox.showMessageBox(welcomeString, true, true);
				MainTimeLine.root.main.townHallPanel.volunteerPanel.messageBox.setShareText("Hey guys, I have just login to SG Cares through The Farmer's Tale. Join me and let's volunteer together!");

				// hide login (no need anymore)
				MainTimeLine.root.main.townHallPanel.volunteerPanel.hideLoginButton();
				
				// check event list whether user signed up
				checkAllUserActivityStatus();
			}
		}
		
		// check loaded activities, see status of user for each activity
		public function checkAllUserActivityStatus(){
			
			if(activityTable == null || activityTable.length == 0)
				return;

			MainTimeLine.root.main.townHallPanel.volunteerPanel.loadingPanel.startLoading();
			MainTimeLine.loadedVolunteerEvents = false;
			
			for(var i:int = 0; i<activityTable.length; i++){
				loadingMutex++;
				SGCareCommunicationModule.checkEventStatus(activityTable[i].activityID);
			}
		}
		
		// set activity status, whether player has signed up, cancelled, etc...
		public function setActivityStatus(activityID:String, statusString:String){
			
			loadingMutex--;

			var i, activityIndex:int = 0;
			
			// loop through activityTable to find the correct index
			for(i = 0;i<activityTable.length; i++){
				if(activityTable[i].activityID == activityID){
					activityIndex = i;
					break;
				}
			}
			
			// not found
			if(activityIndex == activityTable.length)
				return;
			
			activityTable[activityIndex].status = statusString;
			MainTimeLine.root.main.townHallPanel.volunteerPanel.activityTable[activityIndex].status = statusString;
			
			// update day item		
			var activityDate:Date = Utilities.getEventDate(activityTable[activityIndex].date);

			var closeDate:Date = new Date();
			closeDate.setDate( closeDate.getDate() + 3);
			
			var activityDateInMonth:int = activityDate.getDate() - 1;
			
			var dayArray:Array = MainTimeLine.root.main.townHallPanel.volunteerPanel.calendar.dayArray;
			
			for(i = 0; i<dayArray[activityDateInMonth].dayActivityArray.length; i++){
				if(dayArray[activityDateInMonth].dayActivityArray[i].activityID == activityID){ // found

					// check whether is still available or not
					// attended
					if(statusString == ATTENDED){
						dayArray[activityDateInMonth].dayActivityArray[i].status = statusString;
						dayArray[activityDateInMonth].activityComponent.gotoAndStop("notAvailable");
					}
					// registration closed
					else if( activityDate < closeDate ){
						dayArray[activityDateInMonth].dayActivityArray[i].status = "Closed";
						dayArray[activityDateInMonth].activityComponent.gotoAndStop("notAvailable");
					}
					// no status
					else if( statusString == "" ){
						dayArray[activityDateInMonth].dayActivityArray[i].status = "Available";
						dayArray[activityDateInMonth].activityComponent.gotoAndStop("available");
					}
					else{
						dayArray[activityDateInMonth].dayActivityArray[i].status = statusString;
						
						// change calendar day color
						if(statusString == "waitlist" || statusString == "signup")
							dayArray[activityDateInMonth].activityComponent.gotoAndStop("signedUp");
						else if(statusString == "cancelled")
							dayArray[activityDateInMonth].activityComponent.gotoAndStop("available");
					}

					break;
				}
			}

			// check whether other activities in this day have been signed up
			for(i = 0; i<dayArray[activityDateInMonth].dayActivityArray.length; i++){
				if(activityDate > closeDate && (dayArray[activityDateInMonth].dayActivityArray[i].status == "waitlist" || dayArray[activityDateInMonth].dayActivityArray[i].status == "signup") ){ // found
					dayArray[activityDateInMonth].activityComponent.gotoAndStop("signedUp");
					break;
				}
			}

			// update events panel
			var eventsPanel:MovieClip = MainTimeLine.root.main.townHallPanel.volunteerPanel.volunteerEventsPanel;
			if(eventsPanel.eventsArray != null && eventsPanel.eventsArray[0] is ActivityItem){
				
				for(i = 0; i<eventsPanel.eventsArray.length; i++){
					if(eventsPanel.eventsArray[i].activity.activityID == activityID){
						
						eventsPanel.eventsArray[i].activity.status = statusString;
						eventsPanel.infoPanel.setInfo(eventsPanel.eventsArray[i].activity, null);
						
						if(activityDate < closeDate)
							eventsPanel.eventsArray[i].bg.gotoAndStop("notAvailable");
						else if(statusString == "signup" || statusString == "waitlist")
							eventsPanel.eventsArray[i].bg.gotoAndStop("signedUp");
						else
							eventsPanel.eventsArray[i].bg.gotoAndStop("volunteer");
						break;
					}
				}
			}

			MainTimeLine.loadedVolunteerEvents = true;

			if(loadingMutex == 0){
				MainTimeLine.root.main.townHallPanel.volunteerPanel.loadingPanel.stopLoading();
			}
		}
		
		// load previous month activities
		public function loadPreviousMonthActivities(){
			currentDate.setMonth(currentDate.getMonth() - 1);
			loadEvents(currentDate.getMonth(), currentDate.getFullYear());
		}
		
		// load next month activities
		public function loadNextMonthActivities(){
			currentDate.setMonth(currentDate.getMonth() + 1);
			loadEvents(currentDate.getMonth(), currentDate.getFullYear());
		}
		
		// check friends who are joining this activity (if activity player list has been loaded)
		public function searchFriendsInActivity(){
			if(MainTimeLine.loadedPlayerActivityJoin){
				
				// search for friends
				for(var i:int = 0; i<playerActivityJoinTable.length; i++){
					for(var j:int = 0; j<MainTimeLine.friends.length; j++){
						
						// found matching friends id
						if(playerActivityJoinTable[i].playerID == MainTimeLine.friends[j].uid){
							
							// search for activities
							for(var k:int = 0; k<playerActivityJoinTable[i].activityID.length; k++){
								for(var l:int = 0; l<activityTable.length; l++){
									
									// matched activityID, add it and search for next activity
									if(playerActivityJoinTable[i].activityID[k] == activityTable[l].activityID){
										activityTable[l].friends.push(MainTimeLine.friends[j]);
										break;
									}
								}
							}
						}
					}
				}
			}
		}

		// set activities which player joined table
		public function setPlayerActivityJoin(loadedData:Array){
			
			playerActivityJoinTable = [];

			for(var i:int = 0; i < loadedData.length; i++){
				playerActivityJoinTable.push(new PlayerActivityJoin(loadedData[i].playerID, loadedData[i].activityID_signedUp));
			}

		}
		
		// bring player to the url when player clicks sgcares link
		public function sgCaresLinkClick(isVolunteer:Boolean, url:String){
			// check whether player is volunteer
			SGCareCommunicationModule.SGCaresCheckVolunteer(isVolunteer, url);
		}
	}
}